package com.ffapp.helper.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import com.ffapp.helper.R;
import com.ffapp.helper.basis.BasisActivity;
import com.ffapp.helper.basis.BasisApp;
import com.ffapp.helper.basis.BasisFragment;
import com.ffapp.helper.basis.Constants;
import com.ffapp.helper.home.HomeIndexView;
import com.ffapp.helper.util.OwnerConfirmDialog;
import com.leon.lfilepickerlibrary.LFilePicker;
import com.leon.lfilepickerlibrary.utils.Constant;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.io.File;
import java.util.List;

import butterknife.OnClick;
import my.BleUtils;
import my.DialogUtils;
import my.FileUtils;
import my.LogUtil;
import my.TimeUtils;

public class OutAndInFragment extends BasisFragment {

    public static final String FILE_FOLDER_UPDATE = Constants.DIR_UPDATE;
    private HomeIndexView homeIndexView;

    static OutAndInFragment fragment;

    public static OutAndInFragment newInstance(HomeIndexView homeIndexView) {
        if(fragment == null){
            fragment = new OutAndInFragment();
            fragment.homeIndexView = homeIndexView;
        }
        return fragment;
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_out_and_in);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
    }


    private final int REQUEST_READ_FILE_CHOOSE = 41;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.i("onActivityResult---requestCode>"+requestCode);
        if (resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续
//            Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
//            String path = FileUtils.getPathFromUri(mContext,uri);
            String path = null;
            List<String> list = data.getStringArrayListExtra(Constant.RESULT_INFO);
            if(list == null || list.size() == 0){
            }else {
                path = list.get(0);
            }
            LogUtil.i("path-getPathFromUri-->"+path);
            if(TextUtils.isEmpty(path)){
                DialogUtils.DialogOkMsg(mContext,"读取文档失败");
                return;
            }
            File file = new File(path);
            String filttype = FileUtils.getMIMEType(file);
            if(!filttype.startsWith("text/")){
                DialogUtils.DialogOkMsg(mContext,"请选择文本文档");
                return;
            }
            try {
               String result =  FileUtils.ConvertCodeAndGetText(path);
                LogUtil.i("result-->"+result);
                homeIndexView.showAtShowString(result,Constants.AT_FROM_FILE);
            } catch (Exception e) {
                LogUtil.e( e.getMessage());
                DialogUtils.DialogOkMsg(mContext,"解析文档失败");
            }
        }

    }

    @OnClick({R.id.view_out, R.id.view_in})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.view_out:
                sendAtShow();
                break;
            case R.id.view_in:
                checkFilePermission();
                break;
        }
    }

    public void checkFilePermission(){

        Acp.getInstance(mContext).request(new AcpOptions.Builder()
                        .setPermissions(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                                , Manifest.permission.READ_EXTERNAL_STORAGE
                        ).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {

//                        File file = new File(FILE_FOLDER_UPDATE);
////                        Uri uri;
////                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
////                            uri = Uri.fromFile(file);
////                        } else {
//////                            uri = FileProvider.getUriForFile(mContext, mContext.getPackageName(), file);
////                            uri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".provider", file);
////                        }
//                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                        intent.addCategory(Intent.CATEGORY_OPENABLE);
//                        intent.setType("file/");
////                        intent.setDataAndType(uri, "*/*");
//                        startActivityForResult(intent, REQUEST_READ_FILE_CHOOSE);

                        new LFilePicker()
                                .withSupportFragment(OutAndInFragment.this)
                                .withRequestCode(REQUEST_READ_FILE_CHOOSE)
                                .withTitle("文件选择")
                                .withBackgroundColor("#0396FF")
                                .withMutilyMode(false)
                                .withMaxNum(1)
//                                .withStartPath("/storage/emulated/0/Download")//指定初始显示路径
                                .withStartPath(FILE_FOLDER_UPDATE)//指定初始显示路径
//                                .withNotFoundBooks("至少选择一个文件")
//                                .withChooseMode(false)//文件夹选择模式
                                .withFileFilter(new String[]{"txt", "docx"})
                                .start();
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        BasisApp.showToast(permissions.toString() + "权限拒绝");

                    }
                });
    }

    public void sendAtShow() {
        BleUtils.sendAtShow(mContext,new BleUtils.BleUtilCallBack() {
            @Override
            public void onWriteFailure(String message) {
                showToast(""+message);
            }

            @Override
            public void onSuccess(String message) {
                dismissProgress();
                showToast(message);
            }

            @Override
            public void onError(String message) {
                showToast(""+message);
                dismissProgress();
            }

            @Override
            public void onResult(StringBuffer message) {
                outFile(message);
            }

            @Override
            public void onByte(byte[] bytes) {

            }
        });
    }

    public void outFile(final StringBuffer message){

        OwnerConfirmDialog dialog = new OwnerConfirmDialog((BasisActivity) mContext, new OwnerConfirmDialog.OnNamePostListener() {
            @Override
            public void onNamePost(String name) {
                try {
                    String time = TimeUtils.getTimeLongToStrByFormat(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
                    String fileName = FILE_FOLDER_UPDATE + name + ".txt";
                    FileUtils.cacheString(""+fileName, ""+message.toString());
                    showToast("导出成功");
                }catch (Exception e ){
                    showToast("导出失败");
                }
            }
        },"文件名称");
        dialog.show();


    }


}
